<?php
namespace app\common\shopify;
use app\api\model\LogisticsOrder;
use app\api\model\LogisticsOrderItem;
use app\api\model\OrderItem;
use PhpParser\Node\Expr\Isset_;
use think\facade\Db;
use think\facade\Log;

class FulfillmentService extends BaseClient
{
    private $carrierCodeMap = [
        'DHL' => 'DHL',
        'USPS' => 'USPS',
        'UPS' => 'UPS',
        'FedEx' => 'FedEx',
        '顺丰' => 'SF_EXPRESS'
    ];

    /**
     * 统一发货入口（新增）
     */
    public function createOrUpdateFulfillment(array $requestData)
    {
        if($requestData['type'] ?? '' == 'update'){
            #更新物流信息
            [$fulfillmentId, $carrierCode] = $this->getUpdateData($requestData);
            if(!$fulfillmentId || !$carrierCode){
                Log::info(" [shopify] [FulfillmentService] 参数不对不能更新shopify，ID: {$fulfillmentId}  物流：{$carrierCode}");
            }
            return $this->updateFulfillmentTracking($fulfillmentId,$requestData['logistics_no'],$carrierCode);
        }
        // +++ 新增日志 +++
        Log::info(" [shopify] [FulfillmentService] 开始处理发货请求，订单ID: {$requestData['order_id']}");

        // === 新增：转换数据 ===
        $shopifyData = $this->convertSystemDataToShopify($requestData);
        Log::info(" [shopify] [数据转换完成] Shopify订单ID: {$shopifyData['shopify_order_id']}, 物流单号: {$shopifyData['tracking_number']}");

        // === 决定调用哪个方法 ===
        $trackingNumber = $requestData['logistics_no'] ?? '';
        $lineItems = $shopifyData['lineItems'] ?? [];
        $shopifyOrderId = $shopifyData['shopify_order_id'] ?? null;
        $carrierCode = $shopifyData['carrier_code'] ?? '';
        $this->validateLineItems($shopifyOrderId, $lineItems);
        $logistics_order = $requestData['logistics_order'];

        $fulfillmentOrderId =$shopifyData['fulfillmentOrderId'];
        Log::info(" [shopify] [履约订单] 履约订单ID: {$fulfillmentOrderId}");

        // === 新逻辑：如果无物流信息，创建无物流发货 ===
        if (empty($trackingNumber)) {
            Log::info(" [shopify] [无物流发货] 开始创建无物流发货");
            return $this->createFulfillmentWithoutTracking($fulfillmentOrderId, $lineItems,$requestData);
        }

        // === 尝试创建带物流的发货 ===
        try {
            Log::info(" [shopify] [带物流发货] 开始创建发货，物流公司: {$carrierCode}, 单号: {$trackingNumber}");
            return $this->createFulfillmentWithTracking(
                $fulfillmentOrderId,
                $trackingNumber,
                $carrierCode,
                $lineItems,$requestData
            );
        } catch (\Exception $e) {
            // === 新逻辑：处理部分发货的情况 ===
            Log::info(" [shopify] [发货异常] 错误信息: {$e->getMessage()}");

            throw $e;
        }
    }
    private function getUpdateData($requestData)
    {
        Log::info(" [shopify] [数据转换] 开始转换本地数据到Shopify格式，订单ID: {$requestData['order_id']}");

        // 获取Shopify订单ID和映射数据
        $relation = Db::name('order_shopify_relation')
            ->where('order_id', $requestData['order_id'])
            ->field('shopify_order_id, itemdetail')
            ->find();
        if (!$relation || !$relation['shopify_order_id']) {
            $msg = "未找到Shopify订单关联数据: {$requestData['order_id']}";
            Log::error(" [shopify] " ." [shopify] ".$msg);
            throw new \Exception($msg);
        }
        $relationMap = [];
        $shopifyOrderId = $relation['shopify_order_id'];
        if(isset($relation['itemdetail']) && $relation['itemdetail']){
            $relationMap = json_decode($relation['itemdetail'], true)['logistics_fulfillment'] ?? [];
        }
        $fulfillmentId = '';
        if($relationMap){
            foreach ($relationMap as $k=>$v){
               if(isset($v[$requestData['logistics_order']])){
                   $fulfillmentId = $v[$requestData['logistics_order']];
               }
            }
        }
        Log::info(" [shopify] [订单映射] 找到Shopify订单ID: {$shopifyOrderId}, 映射项数: ".count($relationMap));
        // 转换物流公司代码
        $carrierCode = $this->getMappedCarrierCode($requestData['company_id'] ?? 0);
        Log::info(" [shopify] [物流公司] 物流公司ID:{$requestData['company_id']} -> 代码:{$carrierCode}");

        return [$fulfillmentId,$carrierCode];
    }
    /**
     * 转换本地数据到Shopify格式（支持多次调用发货）
     */
    private function convertSystemDataToShopify(array $requestData): array
    {
        Log::info(" [shopify] [数据转换] 开始转换本地数据到Shopify格式，订单ID: {$requestData['order_id']}");

        // 获取Shopify订单ID和映射数据
        $relation = Db::name('order_shopify_relation')
            ->where('order_id', $requestData['order_id'])
            ->field('shopify_order_id, itemdetail')
            ->find();

        if (!$relation || !$relation['shopify_order_id']) {
            $msg = "未找到Shopify订单关联数据: {$requestData['order_id']}";
            Log::error(" [shopify] " .$msg);
            throw new \Exception($msg);
        }

        $shopifyOrderId = $relation['shopify_order_id'];
        $relationMap = json_decode($relation['itemdetail'], true)['iterm_relation'] ?? [];
        Log::info(" [shopify] [订单映射] 找到Shopify订单ID: {$shopifyOrderId}, 映射项数: ".count($relationMap));

        // 实时获取当前所有FulfillmentOrder的最新状态（包括剩余数量）
        $fulfillmentOrderData = $this->getFulfillmentOrderLineItemsV2($shopifyOrderId);

        if (empty($fulfillmentOrderData)) {
            $msg = "未找到订单 {$shopifyOrderId} 的FulfillmentOrder数据";
            Log::error(" [shopify] " .$msg);
            throw new \Exception($msg);
        }

        // 建立FulfillmentOrderLineItem的快速查找映射
        $fulfillmentLineItemMap = [];
        foreach ($fulfillmentOrderData as $item) {
            $fulfillmentLineItemMap[$item['fulfillment_order_line_item_id']] = $item;
        }

        // 处理本次发货的商品行
        $lineItemsToFulfill = [];
        $fulfillmentOrderGroups = [];
        $lineItems = [];
        foreach ($requestData['list'] as $item) {
            $localOrderItemId = $item['id'];
            $requestedQuantity = $item['ship_quantity'];

            Log::info(" [shopify] [处理商品行] 本地订单项ID: {$localOrderItemId}, 请求发货数量: {$requestedQuantity}");

            // 在映射关系中查找对应的FulfillmentOrderLineItem
            $found = false;

            foreach ($relationMap as $mapItem) {
                if ($mapItem['local_order_item_id'] == $localOrderItemId) {
                    $fulfillmentIds = $mapItem['fulfillment_ids'] ?? [];

                    foreach ($fulfillmentIds as $fulfillmentLineItemId) {
                        if (!isset($fulfillmentLineItemMap[$fulfillmentLineItemId])) {
                            Log::info(" [shopify] [映射查找] FulfillmentOrderLineItem不存在: {$fulfillmentLineItemId}");
                            continue;
                        }

                        $fulfillmentItem = $fulfillmentLineItemMap[$fulfillmentLineItemId];
                        $remainingQuantity = $fulfillmentItem['remaining_quantity'];
                        $fulfillmentOrderId = $fulfillmentItem['fulfillment_order_id'];
                        $fulfillmentOrderStatus = $fulfillmentItem['fulfillment_order_status'];

                        Log::info(" [shopify] [剩余数量检查] FulfillmentOrderLineItem: {$fulfillmentLineItemId}, 剩余数量: {$remainingQuantity}, 状态: {$fulfillmentOrderStatus}");

                        // 检查是否还有剩余可发货数量
                        if ($remainingQuantity <= 0) {
                            Log::info(" [shopify] [跳过] FulfillmentOrderLineItem {$fulfillmentLineItemId} 剩余数量为0");
                            continue;
                        }

                        // 检查FulfillmentOrder状态是否允许发货
                        if (!in_array($fulfillmentOrderStatus, ['OPEN', 'IN_PROGRESS'])) {
                            Log::info(" [shopify] [状态检查] FulfillmentOrder {$fulfillmentOrderId} 状态为 {$fulfillmentOrderStatus}，不能发货");
                            continue;
                        }

                        // 计算本次实际可发货数量
                        $actualShipQuantity = min($requestedQuantity, $remainingQuantity);

                        if ($actualShipQuantity > 0) {
                            // 按FulfillmentOrder分组
                            if (!isset($fulfillmentOrderGroups[$fulfillmentOrderId])) {
                                $fulfillmentOrderGroups[$fulfillmentOrderId] = [
                                    'fulfillment_order_id' => $fulfillmentOrderId,
                                    'status' => $fulfillmentOrderStatus,
                                    'line_items' => []
                                ];
                            }

                            $fulfillmentOrderGroups[$fulfillmentOrderId]['line_items'][] = [
                                'id' => $fulfillmentLineItemId,
                                'quantity' => $actualShipQuantity,
//                                'local_order_item_id' => $localOrderItemId,
//                                'remaining_quantity' => $remainingQuantity,
//                                'requested_quantity' => $requestedQuantity
                            ];
                            $lineItems[] = [
                                'id' => $fulfillmentLineItemId,
                                'quantity' => $actualShipQuantity,
//
                            ];
                            Log::info(" [shopify] [发货分配] 本地订单项:{$localOrderItemId} -> FulfillmentOrderLineItem:{$fulfillmentLineItemId}, 分配数量:{$actualShipQuantity}");

                            $found = true;
                            $requestedQuantity -= $actualShipQuantity;

                            // 如果已经分配完所有请求的数量，跳出循环
                            if ($requestedQuantity <= 0) {
                                break;
                            }
                        }
                    }

                    if ($found) {
                        // 如果还有未分配的数量，记录警告
                        if ($requestedQuantity > 0) {
                            Log::info(" [shopify] [数量不足] 本地订单项:{$localOrderItemId} 还有 {$requestedQuantity} 数量无法分配");
                        }
                        break;
                    }
                }
            }

            if (!$found) {
                $msg = "本地订单项 {$localOrderItemId} 没有找到可发货的Shopify映射或剩余数量为0";
                Log::error(" [shopify] " .$msg);
                throw new \Exception($msg);
            }
        }

        // 转换物流公司代码
        $carrierCode = $this->getMappedCarrierCode($requestData['logistics_company'] ?? 0);
        Log::info(" [shopify] [物流公司] 物流公司ID:{$requestData['logistics_company']} -> 代码:{$carrierCode}");

        Log::info(" [shopify] [转换完成] 共生成 " . count($fulfillmentOrderGroups) . " 个FulfillmentOrder发货组");
        $fulfillmentOrderGroups = array_values($fulfillmentOrderGroups);
        return [
            'shopify_order_id' => $shopifyOrderId,
            'carrier_code' => $carrierCode,
            'tracking_number' => $requestData['logistics_no'] ?? '',
            'lineItems' => $lineItems,
            'fulfillmentOrderId' => $fulfillmentOrderGroups[0]['fulfillment_order_id'] ?? '',
            'fulfillment_groups' => $fulfillmentOrderGroups
        ];
    }

    public function getFulfillmentOrderLineItemsV2(string $orderId): array
    {
        Log::info(" [shopify] [获取履约行项V2] 开始查询Shopify订单行项，订单ID: {$orderId}");
        // 方案1：使用includeClosed参数查询所有状态的FulfillmentOrder
        $query = <<<GRAPHQL
query (\$query: String, \$first: Int, \$includeClosed: Boolean) {
    fulfillmentOrders(
        query: \$query
        first: \$first
        includeClosed: \$includeClosed
    ) {
        edges {
            node {
                id
                status
                orderId
                orderName
                lineItems(first: \$first) {
                    edges {
                        node {
                            id
                            totalQuantity
                            remainingQuantity
                            productTitle
                            variantTitle
                            lineItem {
                                id
                                title
                                quantity
                            }
                        }
                    }
                }
                fulfillments(first: \$first) {
                    edges {
                        node {
                            id
                            status
                            fulfillmentLineItems(first: \$first) {
                                edges {
                                    node {
                                        id
                                        quantity
                                        lineItem {
                                            id
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
GRAPHQL;

        $variables = [
            'query' => "order_id:{$orderId}",  // 按订单ID过滤
            'first' => 50,
            'includeClosed' => true  // 包含已关闭的FulfillmentOrder
        ];

        $response = $this->executeGraphQLRequest($query, $variables);

        return $this->extractLineItemsForFulfillmentV2($response);
    }

    /**
     * 提取FulfillmentOrderLineItem信息（V2版本）
     */
    private function extractLineItemsForFulfillmentV2(array $response): array
    {
        $result = [];

        if (empty($response['fulfillmentOrders']['edges'])) {
            Log::info(" [shopify] [获取履约行项V2] 未找到任何FulfillmentOrder");
            return $result;
        }

        foreach ($response['fulfillmentOrders']['edges'] as $fulfillmentOrderEdge) {
            $fulfillmentOrder = $fulfillmentOrderEdge['node'];

            Log::info(" [shopify] [获取履约行项V2] FulfillmentOrder状态", [
                'fulfillment_order_id' => $fulfillmentOrder['id'],
                'status' => $fulfillmentOrder['status'],
                'order_name' => $fulfillmentOrder['orderName']
            ]);

            if (empty($fulfillmentOrder['lineItems']['edges'])) {
                continue;
            }

            foreach ($fulfillmentOrder['lineItems']['edges'] as $lineItemEdge) {
                $lineItem = $lineItemEdge['node'];

                $result[] = [
                    'fulfillment_order_id' => $fulfillmentOrder['id'],
                    'fulfillment_order_status' => $fulfillmentOrder['status'],
                    'fulfillment_order_line_item_id' => $lineItem['id'],
                    'line_item_id' => $lineItem['lineItem']['id'],
                    'product_title' => $lineItem['productTitle'],
                    'variant_title' => $lineItem['variantTitle'],
                    'total_quantity' => $lineItem['totalQuantity'],
                    'remaining_quantity' => $lineItem['remainingQuantity'],
                    'original_line_item' => [
                        'id' => $lineItem['lineItem']['id'],
                        'title' => $lineItem['lineItem']['title'],
                        'quantity' => $lineItem['lineItem']['quantity']
                    ],
                    // 添加发货历史记录
                    'fulfillment_history' => $this->extractFulfillmentHistory($fulfillmentOrder['fulfillments']['edges'] ?? [])
                ];
            }
        }

        Log::info(" [shopify] [获取履约行项V2] 提取完成", ['total_items' => count($result)]);

        return $result;
    }

    /**
     * 提取发货历史记录
     */
    private function extractFulfillmentHistory(array $fulfillmentEdges): array
    {
        $history = [];

        foreach ($fulfillmentEdges as $fulfillmentEdge) {
            $fulfillment = $fulfillmentEdge['node'];

            $fulfillmentLineItems = [];
            if (!empty($fulfillment['fulfillmentLineItems']['edges'])) {
                foreach ($fulfillment['fulfillmentLineItems']['edges'] as $lineItemEdge) {
                    $lineItem = $lineItemEdge['node'];
                    $fulfillmentLineItems[] = [
                        'id' => $lineItem['id'],
                        'quantity' => $lineItem['quantity'],
                        'line_item_id' => $lineItem['lineItem']['id']
                    ];
                }
            }

            $history[] = [
                'fulfillment_id' => $fulfillment['id'],
                'status' => $fulfillment['status'],
                'line_items' => $fulfillmentLineItems
            ];
        }

        return $history;
    }

    // === 新增：获取首个发货单ID ===
    private function getFirstFulfillmentId(string $shopifyOrderId): string
    {
        Log::info(" [shopify] [获取发货单] 查询首个发货单ID，订单ID: {$shopifyOrderId}");
        $query = <<<GRAPHQL
        query GetFulfillments(\$orderId: ID!) {
            order(id: \$orderId) {
                fulfillments(first: 1) {
                    edges {
                        node {
                            id
                        }
                    }
                }
            }
        }
        GRAPHQL;

        $response = $this->graphqlRequest($query, [
            'orderId' => "gid://shopify/Order/{$shopifyOrderId}"
        ]);

        $fulfillments = $response['data']['order']['fulfillments']['edges'] ?? [];

        if (empty($fulfillments)) {
            $msg = "未找到可用的发货单";
            Log::error(" [shopify] " .$msg);
            throw new \Exception($msg);
        }

        $fulfillmentId = $fulfillments[0]['node']['id'];
        Log::info(" [shopify] [发货单获取] 首个发货单ID: {$fulfillmentId}");
        return $fulfillmentId;
    }

    private function getMappedCarrierCode(int $companyId): string
    {
        Log::info(" [shopify] [物流代码] 转换物流公司ID: {$companyId}");
        $companyName = Db::name('logistics_company')
            ->where('id', $companyId)
            ->value('name');

        $code = $this->carrierCodeMap[$companyName] ?? $companyName;
        Log::info(" [shopify] [物流代码] 公司名称:{$companyName} -> 代码:{$code}");
        return $code;
    }

    private function generateTrackingUrl(string $carrier, string $trackingNumber): string
    {
        $url = '';
        $carriers = [
            'DHL' => 'https://www.dhl.com/track?num=',
            'USPS' => 'https://tools.usps.com/go/TrackConfirm?tLabels=',
            'UPS' => 'https://www.ups.com/track?tracknum=',
            'FedEx' => 'https://www.fedex.com/fedextrack/?tracknumbers=',
            'SF_EXPRESS' => 'https://www.sf-express.com/cn/sc/dynamic_function/waybill/#search/bill-number/'
        ];
        if($carriers[$carrier] ?? ''){
            $url = ($carriers[$carrier] ?? '') . $trackingNumber;
        }
        Log::info(" [shopify] [物流链接] 生成追踪URL: {$url}");
        return $url;
    }

    /**
     * 创建带物流信息的发货
     */
    public function createFulfillmentWithTracking(
        string $fulfillmentOrderId,
        string $trackingNumber,
        string $carrierCode,
        array $lineItems,
        $requestData
    ) {
        Log::info(" [shopify] [创建发货] 开始创建带物流的发货，订单发货ID: {$fulfillmentOrderId}");

        $mutation = <<<GRAPHQL
    mutation FulfillmentCreateV2(\$fulfillment: FulfillmentV2Input!) {
        fulfillmentCreateV2(fulfillment: \$fulfillment) {
            fulfillment { 
                id 
                status
                trackingInfo {
                    number
                    company
                    url
                }
            }
            userErrors { 
                field 
                message 
            }
        }
    }
    GRAPHQL;

        $variables = [
            'fulfillment' => [
                'lineItemsByFulfillmentOrder' => [[
                    'fulfillmentOrderId' => $fulfillmentOrderId,
                    'fulfillmentOrderLineItems' => $lineItems
                ]],
                'trackingInfo' => [
                    'company' => $carrierCode,
                    'number' => $trackingNumber,
                ],
                'notifyCustomer' => true
            ]
        ];
        if($this->generateTrackingUrl($carrierCode, $trackingNumber)){
            $variables['fulfillment']['trackingInfo']['url']  = $this->generateTrackingUrl($carrierCode, $trackingNumber);
        }
        Log::info(" [shopify] [GraphQL请求] 发货创建Mutation: ".json_encode($variables));
        $response = $this->executeGraphQLRequest($mutation, $variables);

        // 检查 GraphQL 错误
        if (isset($response['fulfillmentCreateV2']['userErrors']) &&
            !empty($response['fulfillmentCreateV2']['userErrors'])) {
            $errors = $response['fulfillmentCreateV2']['userErrors'];
            $errorMessages = array_map(function($error) {
                return $error['message'];
            }, $errors);

            Log::error(" [shopify] " ."[发货创建失败] 错误: " . implode(', ', $errorMessages));
            throw new \Exception("创建发货失败: " . implode(', ', $errorMessages));
        }

        // 检查是否成功创建发货
        if (isset($response['fulfillmentCreateV2']['fulfillment']['id'])) {
            Log::info(" [shopify] [发货创建成功] 发货ID: " . $response['fulfillmentCreateV2']['fulfillment']['id']);
            $this->updateRelation($response, $requestData);
            return $response;
        }

        // 如果到这里，说明发生了未知错误
        Log::error(" [shopify] " ."[发货创建失败] 未知错误: " . json_encode($response));
        throw new \Exception("创建发货失败: 未知错误");
    }

    // === 新增：检测创建发货时的特定错误 ===
    private function isFulfillmentCreateError(array $response): bool
    {
        if (empty($response['userErrors'])) return false;

        foreach ($response['userErrors'] as $error) {
            if (strpos($error['message'], 'already exists') !== false ||
                strpos($error['message'], '无法创建新发货') !== false) {
                Log::info(" [shopify] [发货错误] 特定错误: {$error['message']}");
                return true;
            }
        }
        return false;
    }

    /**
     * 创建无物流信息的发货
     */
    public function createFulfillmentWithoutTracking(
        string $fulfillmentOrderId,
        array $lineItems,$requestData
    ) {
        Log::info(" [shopify] [无物流发货] 开始创建，履约订单ID: {$fulfillmentOrderId}");
        $mutation = <<<GRAPHQL
    mutation FulfillmentCreateV2(\$fulfillment: FulfillmentV2Input!) {
        fulfillmentCreateV2(fulfillment: \$fulfillment) {
            fulfillment { 
                id 
                status
            }
            userErrors { 
                field 
                message 
            }
        }
    }
    GRAPHQL;

        $variables = [
            'fulfillment' => [
                'lineItemsByFulfillmentOrder' => [[
                    'fulfillmentOrderId' => $fulfillmentOrderId,
                    'fulfillmentOrderLineItems' => $lineItems
                ]],
                'notifyCustomer' => false
            ]
        ];

        Log::info(" [shopify] [GraphQL请求] 无物流发货Mutation: ".json_encode($variables));
        $response = $this->executeGraphQLRequest($mutation, $variables);
        if(isset($response['fulfillmentCreateV2']['fulfillment']['status']) && $response['fulfillmentCreateV2']['fulfillment']['status'] == 'SUCCESS'){
            $this->updateRelation($response,$requestData);
        }
        Log::info(" [shopify] [无物流发货成功] 响应: ".json_encode($response));
        return $response;
    }
    private function updateRelation($response,$requestData)
    {
        // 获取Shopify订单ID和映射数据
        $relation = Db::name('order_shopify_relation')
            ->where('order_id', $requestData['order_id'])
            ->field('shopify_order_id, itemdetail')
            ->find();
        $itemdetail = $relation['itemdetail'];
        $itemdetail = json_decode($itemdetail,true);
        $itemdetail['logistics_fulfillment'] = $itemdetail['logistics_fulfillment'] ??[];
       array_push($itemdetail['logistics_fulfillment'],[$requestData['logistics_order'] =>$response['fulfillmentCreateV2']['fulfillment']['id']]);
        Db::name('order_shopify_relation')
            ->where('order_id', $requestData['order_id'])->update(['itemdetail' => json_encode($itemdetail)]);
    }
    /**
     * 更新物流跟踪信息
     */
    public function updateFulfillmentTracking(
        string $fulfillmentId,
        string $trackingNumber,
        string $carrierCode
    ) {
        Log::info(" [shopify] [更新物流] 开始更新发货单: {$fulfillmentId}");
        $mutation = <<<GRAPHQL
        mutation FulfillmentTrackingUpdate(\$fulfillmentId: ID!, \$trackingInfo: FulfillmentTrackingInput!) {
            fulfillmentTrackingInfoUpdateV2(
                fulfillmentId: \$fulfillmentId
                trackingInfoInput: \$trackingInfo
            ) {
                fulfillment { id }
                userErrors { field message }
            }
        }
        GRAPHQL;

        $variables = [
            'fulfillmentId' => $fulfillmentId,
            'trackingInfo' => [
                'company' => $carrierCode,
                'number' => $trackingNumber
            ]
        ];
        if($this->generateTrackingUrl($carrierCode, $trackingNumber)){
            $variables['trackingInfo']['url']  = $this->generateTrackingUrl($carrierCode, $trackingNumber);
        }
        Log::info(" [shopify] [GraphQL请求] 物流更新Mutation: ".json_encode($variables));
        $response = $this->executeGraphQLRequest($mutation, $variables);
        Log::info(" [shopify] [物流更新成功] 响应: ".json_encode($response));
        return $response;
    }

    private function validateLineItems(string $shopifyOrderId, array &$lineItems)
    {
        Log::info(" [shopify] [行项验证] 开始验证行项有效性，订单ID: {$shopifyOrderId}");
        $query = <<<GRAPHQL
        query ValidateLineItems(\$orderId: ID!) {
            order(id: \$orderId) {
                fulfillmentOrders(first: 1) {
                    edges {
                        node {
                            lineItems(first: 50) {
                                edges {
                                    node {
                                        id
                                        remainingQuantity
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        GRAPHQL;

        $response = $this->graphqlRequest($query, [
            'orderId' => "gid://shopify/Order/{$shopifyOrderId}"
        ]);
        $validItems = [];
        if($response['order']['fulfillmentOrders']['edges']){
            foreach ($response['order']['fulfillmentOrders']['edges'] as $order) {
                foreach ($order['node']['lineItems']['edges'] as $item) {
                    $validItems[$item['node']['id']] = $item['node']['remainingQuantity'];
                }
            }
        }

        Log::info(" [shopify] [行项验证] 有效行项数: ".count($validItems));
        $modified = false;

        foreach ($lineItems as &$item) {
            $id = $item['id'] ?? null;

            if (!isset($validItems[$id])) {
                $msg = "无效的LineItem ID: {$id}";
                Log::error(" [shopify] " .$msg);
                throw new \Exception($msg);
            }

            if ($item['quantity'] > $validItems[$id]) {
                $original = $item['quantity'];
                $item['quantity'] = $validItems[$id];
                $modified = true;
                Log::info(" [shopify] 行项{$id} 发货量超出剩余库存 ({$original} > {$validItems[$id]}), 已修正");
            }
        }

        if ($modified) {
            Log::info(" [shopify] [行项修正] 已自动调整超量发货项");
        }
        return 1;
    }

    private function executeGraphQLRequest(string $mutation, array $variables)
    {
        Log::info(" [shopify] [GraphQL请求] 开始执行，操作: ".substr($mutation, 0, 50)."...");
        $response = $this->graphqlRequest($mutation, $variables);

        if (!empty($response['userErrors'])) {
            $errors = json_encode($response['userErrors']);
            Log::error(" [shopify] " ."Shopify API错误: {$errors}");
            throw new \Exception("Shopify操作失败: {$errors}");
        }

        Log::info(" [shopify] [GraphQL响应] 请求成功完成");
        return $response;
    }
}